package com.lord.otter.component.context.spring;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 静态Spring上下文
 *
 * @author lord
 * 2025/7/2 16:07
 */
@Component
public class StaticSpringContext implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        StaticSpringContext.context = applicationContext;
    }


    public static <T> T getBean(Class<T> beanClass) {
        return context.getBean(beanClass);
    }

    public static <T> List<T> getBeanList(Class<T> beanClass) {
        Map<String, T> beansOfType = context.getBeansOfType(beanClass);
        if (CollectionUtils.isEmpty(beansOfType)) {
            return new ArrayList<>();
        }

        return new ArrayList<>(beansOfType.values());
    }


    public static <T> T getBean(String beanName, Class<T> beanClass) {
        return context.getBean(beanName, beanClass);
    }

    public static <T> T getBeansOfType(Class<T> beanClass) {
        Map<String, T> beansOfType = context.getBeansOfType(beanClass);
        if (CollectionUtils.isEmpty(beansOfType)) {
            return null;
        }
        if (beansOfType.size() == 1) {
            return new ArrayList<>(beansOfType.values()).get(0);
        }
        for (T value : beansOfType.values()) {
            if (value.getClass() == beanClass) {
                return value;
            }
        }
        for (T value : beansOfType.values()) {
            if (beanClass.isAssignableFrom(beanClass)) {
                return value;
            }
        }
        return null;
    }

}
